﻿using UnityEditor;
using UnityEngine;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using LuaInterface;

public class Packager {
    public static string platform = string.Empty;
    static List<string> paths = new List<string>();
    static List<string> files = new List<string>();
    static List<AssetBundleBuild> maps = new List<AssetBundleBuild>();

    ///-----------------------------------------------------------
    static string[] exts = { ".txt", ".xml", ".lua", ".assetbundle", ".json" };
    static bool CanCopy(string ext) {   //能不能复制
        foreach (string e in exts) {
            if (ext.Equals(e)) return true;
        }
        return false;
    }

    /// <summary>
    /// 载入素材
    /// </summary>
    static UnityEngine.Object LoadAsset(string file) {
        if (file.EndsWith(".lua")) file += ".txt";
        return AssetDatabase.LoadMainAssetAtPath("Assets/LuaFramework/Examples/Builds/" + file);
    }

    [MenuItem("LuaFramework/Build All Resource", false, 100)]
    static void BuildAllResources(){
        BuildLuaResources();
		BuildAssetResource();
        BuildFileIndex();
    }


    [MenuItem("LuaFramework/Build Lua", false, 101)]
    static void BuildLuaResources(){
        string streamPath = Application.streamingAssetsPath+"/lua";
        if (Directory.Exists(streamPath)) {
            Directory.Delete(streamPath, true);
        }
        Directory.CreateDirectory(streamPath);
        AssetDatabase.Refresh();

        maps.Clear();
//        if (LuaConst.LuaBundleMode)
//        {
            HandleLuaBundle();

            string resPath = "Assets/StreamingAssets";
            BuildPipeline.BuildAssetBundles(resPath, maps.ToArray(), BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
    
            string tempDir = Application.dataPath + "/_lua";
            if (Directory.Exists(tempDir))
                Directory.Delete(tempDir, true);
			tempDir = Application.dataPath + "/" + LuaConst.LuaTempDir;
			if (Directory.Exists(tempDir))
				Directory.Delete(tempDir, true);
		
            AssetDatabase.Refresh();
//        }
//        else
//        {
//            HandleLuaFile();
//        }


        //复制当前项目的脚本到Export目录中
		if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS || EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android)
		{
	        string destFolder = Application.dataPath.Substring(0,Application.dataPath.Length-7)+"/Exports/"+GetFolderByBuildTarget(EditorUserBuildSettings.activeBuildTarget)+"/lua";
	        if (Directory.Exists(destFolder))
	            Directory.Delete(destFolder,true);
	        Directory.CreateDirectory(destFolder);

			string ns = EditorSettings.projectGenerationRootNamespace.ToLower();
			bool isMainApp = ns.Equals("mainapp") || string.IsNullOrEmpty(ns);

	        string[] files = Directory.GetFiles(streamPath);
	        for (int i = 0; i < files.Length; ++i)
			{
				string f = files[i];

	            if (f.IndexOf("lua_" + EditorSettings.projectGenerationRootNamespace.ToLower()) > 0)
	            {

					if(f.EndsWith(".meta") || f.EndsWith(".manifest") ) continue;

	                File.Copy(f, destFolder + "/"+Path.GetFileName(f),true);
	            }
				else if(isMainApp)
				{

					if(f.EndsWith(".meta") || f.EndsWith(".manifest") ) continue;

					File.Copy(f, destFolder + "/"+Path.GetFileName(f),true);
				}
	        }

			if(!isMainApp){
				if(File.Exists(destFolder + "/lua.unity3d")) File.Delete(destFolder + "/lua.unity3d");
				if(File.Exists(destFolder + "/lua.unity3d.manifest")) File.Delete(destFolder + "/lua.unity3d.manifest");
			}
		}
    }

	[MenuItem("LuaFramework/Build Selected Assets", false, 103)]
	static void BuildSelectedAssets(){
		Object[] objs = Selection.GetFiltered(typeof(Object),SelectionMode.DeepAssets);
		if(objs!=null)
		{
			maps.Clear();
			Dictionary<string,List<string>> _temp = new Dictionary<string, List<string>>();
			foreach(var obj in objs){
				string dirPath = AssetDatabase.GetAssetOrScenePath(obj);
				if(string.IsNullOrEmpty(dirPath)==false)
				{
					if (Directory.Exists(dirPath)){
						//遍历下面所有的文件
						string[] files = Directory.GetFiles(Application.dataPath + dirPath.Substring(6),"*.*",SearchOption.AllDirectories);
						foreach(var file in files){
							var url = file.Substring(file.IndexOf(dirPath));
							if(file.EndsWith(".meta")==false && file.EndsWith(".DS_Store")==false ){
								AssetImporter importer = AssetImporter.GetAtPath(url);
								if (importer != null && !string.IsNullOrEmpty(importer.assetBundleName))
								{
									if(!_temp.ContainsKey(importer.assetBundleName)) {
										_temp[importer.assetBundleName] = new List<string>();
									}
									_temp[importer.assetBundleName].Add(url);
									importer.assetBundleName = null;

									CollectDepends(url,_temp);
								}
							}
						}
					}
					else if(File.Exists(dirPath))
					{
						var url = dirPath.Substring(dirPath.IndexOf(dirPath));
						if(dirPath.EndsWith(".meta")==false && dirPath.EndsWith(".DS_Store")==false ){
							AssetImporter importer = AssetImporter.GetAtPath(url);
							if (importer != null && !string.IsNullOrEmpty(importer.assetBundleName))
							{
								if(!_temp.ContainsKey(importer.assetBundleName)) {
									_temp[importer.assetBundleName] = new List<string>();
								}
								_temp[importer.assetBundleName].Add(url);
								importer.assetBundleName = null;

								CollectDepends(url,_temp);
							}
						}
					}
				}
			}



			foreach(string bundleName in _temp.Keys){
				AssetBundleBuild build = new AssetBundleBuild();
				build.assetBundleName = bundleName;

				string[] all = AssetDatabase.GetAssetPathsFromAssetBundle(bundleName);
				var v = _temp[bundleName];
				for(int i = 0;i<all.Length;++i){
					var a = all[i];
					AssetImporter importer = AssetImporter.GetAtPath(a);
					if (importer != null && importer.assetBundleName==bundleName)
					{
						_temp[bundleName].Add(a);
					}
				}
				build.assetNames = _temp[bundleName].ToArray();
				maps.Add(build);
			}
			if(maps.Count>0)
			{
				string resPath = "Assets/StreamingAssets/"+EditorSettings.projectGenerationRootNamespace.ToLower();
				BuildPipeline.BuildAssetBundles(resPath, maps.ToArray(), BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);

				//还原assetbundlename
				foreach(AssetBundleBuild abb in maps){
					foreach(string url in abb.assetNames){
						AssetImporter importer = AssetImporter.GetAtPath(url);
						importer.assetBundleName = abb.assetBundleName;
					}
				}
				maps.Clear();
				AssetDatabase.Refresh();
			}
		}

	}
	static void CollectDepends(string filePath,Dictionary<string,List<string>> _temp){
		string[] files = AssetDatabase.GetDependencies(filePath,true);
		foreach(var url in files){
			if(url.EndsWith(".meta")==false && url.EndsWith(".DS_Store")==false ){
				AssetImporter importer = AssetImporter.GetAtPath(url);
				if (importer != null && !string.IsNullOrEmpty(importer.assetBundleName))
				{
					if(!_temp.ContainsKey(importer.assetBundleName)) {
						_temp[importer.assetBundleName] = new List<string>();
					}
					_temp[importer.assetBundleName].Add(url);
					importer.assetBundleName = null;
//					CollectDepends(file,_temp);
				}
			}
		}
	}

	[MenuItem("LuaFramework/Build Asset Resource", false, 102)]
    /// <summary>
    /// 生成绑定素材
    /// </summary>
    static void BuildAssetResource() {
		string streamPath = Application.streamingAssetsPath+"/"+EditorSettings.projectGenerationRootNamespace.ToLower();
        if (Directory.Exists(streamPath)) {
            Directory.Delete(streamPath, true);
        }
        Directory.CreateDirectory(streamPath);
        AssetDatabase.Refresh();

		BuildPipeline.BuildAssetBundles(streamPath,BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
       
        AssetDatabase.Refresh();

        //复制一份到项目外面
		if(EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS || EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android){
			string dest = Application.dataPath.Substring(0,Application.dataPath.Length-7)+"/Exports/"+GetFolderByBuildTarget(EditorUserBuildSettings.activeBuildTarget)+"/"+EditorSettings.projectGenerationRootNamespace.ToLower();
			if (Directory.Exists(dest))
				Directory.Delete(dest, true);

			CopyDirectory(streamPath,dest,true);

			if (Directory.Exists(streamPath + "raw"))
			{
				dest = dest + "raw";
				if (Directory.Exists(dest))
					Directory.Delete(dest, true);
				CopyDirectory(streamPath + "raw",dest,true);
			}
		}
    }




    [MenuItem("LuaFramework/Build Protobuf-lua-gen File")]
    public static void BuildProtobufFile() {
        string dir = AppDataPath + "/Lua/3rd/pblua";
        paths.Clear(); files.Clear(); Recursive(dir);

        string protoc = "d:/protobuf-2.4.1/src/protoc.exe";
        string protoc_gen_dir = "\"d:/protoc-gen-lua/plugin/protoc-gen-lua.bat\"";

        foreach (string f in files) {
            string name = Path.GetFileName(f);
            string ext = Path.GetExtension(f);
            if (!ext.Equals(".proto")) continue;

            ProcessStartInfo info = new ProcessStartInfo();
            info.FileName = protoc;
            info.Arguments = " --lua_out=./ --plugin=protoc-gen-lua=" + protoc_gen_dir + " " + name;
            info.WindowStyle = ProcessWindowStyle.Hidden;
            info.UseShellExecute = true;
            info.WorkingDirectory = dir;
            info.ErrorDialog = true;
            Util.Log(info.FileName + " " + info.Arguments);

            Process pro = Process.Start(info);
            pro.WaitForExit();
        }
        AssetDatabase.Refresh();
    }


    public static string GetFolderByBuildTarget(BuildTarget tar){
        if (tar == BuildTarget.Android)
            return "Android";
        if (tar == BuildTarget.iOS)
            return "iOS";
        return "PC";
    }

    static void CopyDirectory(string sourceDirName, string destDirName, bool copySubDirs)
    {
        // Get the subdirectories for the specified directory.
        DirectoryInfo dir = new DirectoryInfo(sourceDirName);

        if (!dir.Exists)
        {
            return;
        }

        DirectoryInfo[] dirs = dir.GetDirectories();
        // If the destination directory doesn't exist, create it.
        if (!Directory.Exists(destDirName))
        {
            Directory.CreateDirectory(destDirName);
        }

        // Get the files in the directory and copy them to the new location.
        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files)
        {
			if(file.Name.EndsWith(".meta") ) continue;

			if(file.FullName.EndsWith(".manifest")){
				string folder = Directory.GetParent(file.FullName).Name;
				if(!file.FullName.EndsWith(folder+".manifest")){
					continue;
				}
			}

            string temppath = Path.Combine(destDirName, file.Name);
            file.CopyTo(temppath, true);
        }

        // If copying subdirectories, copy them and their contents to new location.
        if (copySubDirs)
        {
            foreach (DirectoryInfo subdir in dirs)
            {
                string temppath = Path.Combine(destDirName, subdir.Name);
                CopyDirectory(subdir.FullName, temppath, copySubDirs);
            }
        }
    }

    static void AddBuildMap(string bundleName, string pattern, string path) {
        string[] files = Directory.GetFiles(path, pattern);
        if (files.Length == 0) return;

        for (int i = 0; i < files.Length; i++) {
            files[i] = files[i].Replace('\\', '/');
        }
        AssetBundleBuild build = new AssetBundleBuild();
        build.assetBundleName = bundleName;
        build.assetNames = files;
        maps.Add(build);
    }

   
    /// <summary>
    /// 处理Lua代码包
    /// </summary>
    static void HandleLuaBundle() {
        string streamDir = Application.dataPath + "/" + LuaConst.LuaTempDir;
        if (!Directory.Exists(streamDir)) Directory.CreateDirectory(streamDir);

        string[] srcDirs = { Application.dataPath+"/Lua", Application.dataPath + "/LuaFramework/ToLua/Lua" };
        for (int i = 0; i < srcDirs.Length; i++) {
            if (LuaConst.LuaByteMode) {
                string sourceDir = srcDirs[i];
                string[] files = Directory.GetFiles(sourceDir, "*.lua", SearchOption.AllDirectories);
                int len = sourceDir.Length;

                if (sourceDir[len - 1] == '/' || sourceDir[len - 1] == '\\') {
                    --len;
                }
                for (int j = 0; j < files.Length; j++) {
                    string str = files[j].Remove(0, len);
                    string dest = streamDir + str + ".bytes";
                    string dir = Path.GetDirectoryName(dest);
                    Directory.CreateDirectory(dir);
                    EncodeLuaFile(files[j], dest);
                }    
            } else {
                ToLuaMenu.CopyLuaBytesFiles(srcDirs[i], streamDir);
            }
        }
        string[] dirs = Directory.GetDirectories(streamDir, "*", SearchOption.AllDirectories);
        for (int i = 0; i < dirs.Length; i++) {
            string name = dirs[i].Replace(streamDir, string.Empty);
            name = name.Replace('\\', '_').Replace('/', '_');
            name = "lua/lua" + name.ToLower() + LuaConst.ExtName;

            string path = "Assets" + dirs[i].Replace(Application.dataPath, "");
            AddBuildMap(name, "*.bytes", path);
        }
        AddBuildMap("lua/lua" + LuaConst.ExtName, "*.bytes", "Assets/" + LuaConst.LuaTempDir);

        //-------------------------------处理非Lua文件----------------------------------
//        string luaPath = AppDataPath + "/StreamingAssets/lua/";
//        for (int i = 0; i < srcDirs.Length; i++) {
//            paths.Clear(); files.Clear();
//            string luaDataPath = srcDirs[i].ToLower();
//            Recursive(luaDataPath);
//            foreach (string f in files) {
//				if (f.EndsWith(".meta") || f.EndsWith(".lua") || f.EndsWith(".DS_Store") || f.EndsWith(".iml")|| f.EndsWith(".bat")) continue;
//                string newfile = f.Replace(luaDataPath, "");
//                string path = Path.GetDirectoryName(luaPath + newfile);
//                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
//
//                string destfile = path + "/" + Path.GetFileName(f);
//                File.Copy(f, destfile, true);
//            }
//        }
        AssetDatabase.Refresh();
    }

    /// <summary>
    /// 处理Lua文件
    /// </summary>
    static void HandleLuaFile() {
        string resPath = AppDataPath + "/StreamingAssets/";
        string luaPath = resPath + "/lua/";

        //----------复制Lua文件----------------
        if (Directory.Exists(luaPath)) {
            Directory.CreateDirectory(luaPath); 
        }
        string[] luaPaths = { AppDataPath + "/lua/", 
                              AppDataPath + "/LuaFramework/Tolua/Lua/" };

        for (int i = 0; i < luaPaths.Length; i++) {
            paths.Clear(); files.Clear();
            string luaDataPath = luaPaths[i].ToLower();
            Recursive(luaDataPath);
            int n = 0;
            foreach (string f in files) {
                if (f.EndsWith(".meta")) continue;

                string newfile = f.Replace(luaDataPath, "");
                string newpath = luaPath + newfile;
                string path = Path.GetDirectoryName(newpath);
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                if (File.Exists(newpath)) {
                    File.Delete(newpath);
                }
                if (LuaConst.LuaByteMode) {
                    EncodeLuaFile(f, newpath);
                } else {
                    File.Copy(f, newpath, true);
                }
                UpdateProgress(n++, files.Count, newpath);
            } 
        }
        EditorUtility.ClearProgressBar();
        AssetDatabase.Refresh();
    }

    /// <summary>
    /// md5 streamingAssets下面所有文件
    /// </summary>
    [MenuItem("LuaFramework/Md5 Files", false, 200)]
    static void BuildFileIndex() {
        string resPath = AppDataPath + "/StreamingAssets/";

		///-------------------删除一些多余的文件------------------
		if(File.Exists(resPath+"StreamingAssets")){
			File.Delete(resPath+"StreamingAssets");
		}
		if(File.Exists(resPath+"StreamingAssets.manifest")){
			File.Delete(resPath+"StreamingAssets.manifest");
		}
		if(File.Exists(resPath+"StreamingAssets.meta")){
			File.Delete(resPath+"StreamingAssets.meta");
		}
		if(File.Exists(resPath+"StreamingAssets.manifest.meta")){
			File.Delete(resPath+"StreamingAssets.manifest.meta");
		}
		if(File.Exists(resPath + "files.txt")){
			File.Delete(resPath + "files.txt");
		}
		if(File.Exists(resPath + "files.txt.meta")){
			File.Delete(resPath + "files.txt.meta");
		}

        ///----------------------创建文件列表-----------------------

		string rootNS = EditorSettings.projectGenerationRootNamespace.ToLower();
		bool isMainApp = rootNS.Equals("mainapp") || string.IsNullOrEmpty(rootNS);

		string newFilePath = resPath + "/"+rootNS+".txt";
        if (File.Exists(newFilePath)) File.Delete(newFilePath);

        paths.Clear(); files.Clear();
        Recursive(resPath);

        FileStream fs = new FileStream(newFilePath, FileMode.CreateNew);
        StreamWriter sw = new StreamWriter(fs);
        for (int i = 0; i < files.Count; i++) {
            string file = files[i];
			if (file.EndsWith(".meta") || file.Contains(".DS_Store") 
				|| file.IndexOf("google-services")>-1 
				|| file.IndexOf("GoogleService-Info")>-1) 
				continue;

			if(file.EndsWith(".manifest")){
				string folder = Directory.GetParent(file).Name;
				if(!file.EndsWith(folder+".manifest")){
					continue;
				}
			}

            string md5 = Util.md5file(file);
            string value = file.Replace(resPath, string.Empty);
			if (value.IndexOf("/") > 0) //只md5 文件夹下面的，不处理StreamingAssets目录下面的文件
			{
				if(isMainApp && value.StartsWith("lua/lua_comm.unity3d")) {//因为comm经常改动，所以加入md5中
					sw.WriteLine(value + "|" + md5);
					continue;
				}

				if (value.StartsWith("lua/lua_") && value.IndexOf("lua/lua_"+rootNS) == -1 )
				{
					continue;
				}
				if(value.StartsWith("lua/")==false && value.StartsWith(rootNS)==false) continue;
				if(value.Equals("lua/lua_comm.unity3d"))  continue;
				if(value.Equals("lua/lua.unity3d"))  continue;
				if(value.Equals("lua/lua.unity3d.manifest"))  continue;
					
				sw.WriteLine(value + "|" + md5);
			}
        }
        sw.Close(); fs.Close();
        AssetDatabase.Refresh();

		//创建file.txt到Export
		if(EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android || EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS){
			string frameworkFolder = Application.dataPath.Substring(0,Application.dataPath.Length-7)+"/Exports/"+GetFolderByBuildTarget(EditorUserBuildSettings.activeBuildTarget);
			if(File.Exists(frameworkFolder + "/files.txt")){
				File.Delete(frameworkFolder + "/files.txt");
			}
			if(File.Exists(frameworkFolder + "/"+rootNS+".txt")){
				File.Delete(frameworkFolder + "/"+rootNS+".txt");
			}
			File.Copy(newFilePath ,frameworkFolder+ "/"+rootNS+".txt");
		}
    }


    [MenuItem("LuaFramework/MainApp/Calculate Update", false, 0)]
    static void CalculateUpdate(){
        string exportFolder = Application.dataPath.Substring(0, Application.dataPath.Length - 7) + "/Exports/";
        if (!Directory.Exists(exportFolder))
            return;

        string updateZip = exportFolder + (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS ? "ios_update.zip" : "android_update.zip");
        if (File.Exists(updateZip))
        {
            File.Delete(updateZip);
        }
        string oldMd5File = exportFolder + (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS ? "ios.txt" : "android.txt");
        string currFolder = exportFolder + (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS ? "iOS/" : "Android/");
        string newMd5File =  exportFolder + (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS ? "iOS/mainapp.txt" : "Android/mainapp.txt");
        if (!File.Exists(oldMd5File) || !File.Exists(newMd5File))
            return;

        string[] lines = File.ReadAllLines(oldMd5File);
        Dictionary<string,string> oldMd5KV = new Dictionary<string, string>();
        foreach (string line in lines)
        {
            if (line.Length > 2)
            {
                string[] temp = line.Split('|');
                if (temp.Length > 1)
                {
                    oldMd5KV[temp[0]] = temp[1];
                }
            }
        }


        lines = File.ReadAllLines(newMd5File);
        Dictionary<string,string> newMd5KV = new Dictionary<string, string>();
        foreach (string line in lines)
        {
            if (line.Length > 2)
            {
                string[] temp = line.Split('|');
                if (temp.Length > 1)
                {
                    newMd5KV[temp[0]] = temp[1];
                }
            }
        }

       
        string tempFold = exportFolder  + "_temp/";
        if (Directory.Exists(tempFold))
        {
            Directory.Delete(tempFold, true);
        }
        Directory.CreateDirectory(tempFold);
        int count=0;
        foreach (string path in newMd5KV.Keys)
        {
            if (!oldMd5KV.ContainsKey(path) || oldMd5KV[path] != newMd5KV[path])
            {
                string f = tempFold + path.Substring(0, path.LastIndexOf("/"));
                if (!Directory.Exists(f))
                    Directory.CreateDirectory(f);
                File.Copy(currFolder + path, tempFold + path, true);
                ++count;
            }
        }
        //创建 zip
        string pwd = "";
        ZipUtility.Zip(Directory.GetDirectories(tempFold), updateZip, pwd);
        UnityEngine.Debug.Log("有"+count+"个更新文件");

        Directory.Delete(tempFold,true);
    }


    string ReverseStr(string text)
    {
        char[] charArray = text.ToCharArray();
        System.Array.Reverse(charArray);
        return new string(charArray);
    }

    [MenuItem("LuaFramework/MainApp/Md5 and Calculate Update", false, 2)]
    static void Md5AndCalculateUpdate(){
        BuildFileIndex();
        CalculateUpdate();
    }


//	[MenuItem("LuaFramework/Md5 Export IOS Files", false, 512)]
//	static void BuildExportIOSFileIndex() {
//		BuildExportFileIndex(BuildTarget.iOS);
//	}
//	[MenuItem("LuaFramework/Md5 Export Android Files", false, 513)]
//	static void BuildExportAndroidFileIndex() {
//		BuildExportFileIndex(BuildTarget.Android);
//	}


//	static void BuildExportFileIndex(BuildTarget target) {
//		
//		string resPath = Application.dataPath.Substring(0,Application.dataPath.Length-7)+"/Exports/"+GetFolderByBuildTarget(target)+"/";
//
//		///----------------------创建文件列表-----------------------
//		string newFilePath = resPath + "/files.txt";
//		if (File.Exists(newFilePath)) File.Delete(newFilePath);
//
//		paths.Clear(); files.Clear();
//		Recursive(resPath);
//
//		FileStream fs = new FileStream(newFilePath, FileMode.CreateNew);
//		StreamWriter sw = new StreamWriter(fs);
//		for (int i = 0; i < files.Count; i++) {
//			string file = files[i];
//			if (file.EndsWith(".meta") || file.Contains(".DS_Store") 
//				|| file.IndexOf("google-services")>-1 
//				|| file.IndexOf("GoogleService-Info")>-1) 
//				continue;
//
//			string ext = Path.GetExtension(file);
//
//			string md5 = Util.md5file(file);
//			string value = file.Replace(resPath, string.Empty);
//			if(value.IndexOf("Framework")==0){
//				value = value.Replace("Framework","lua");
//			}
//
//			sw.WriteLine(value + "|" + md5);
//		}
//		sw.Close(); fs.Close();
//		AssetDatabase.Refresh();
//	}



    /// <summary>
    /// 数据目录
    /// </summary>
    static string AppDataPath {
        get { return Application.dataPath.ToLower(); }
    }

    /// <summary>
    /// 遍历目录及其子目录
    /// </summary>
    static void Recursive(string path) {
        string[] names = Directory.GetFiles(path);
        string[] dirs = Directory.GetDirectories(path);
        foreach (string filename in names) {
            string ext = Path.GetExtension(filename);
            if (ext.Equals(".meta")) continue;
            files.Add(filename.Replace('\\', '/'));
        }
        foreach (string dir in dirs) {
            paths.Add(dir.Replace('\\', '/'));
            Recursive(dir);
        }
    }

    static void UpdateProgress(int progress, int progressMax, string desc) {
        string title = "Processing...[" + progress + " - " + progressMax + "]";
        float value = (float)progress / (float)progressMax;
        EditorUtility.DisplayProgressBar(title, desc, value);
    }

    public static void EncodeLuaFile(string srcFile, string outFile) {
        if (!srcFile.ToLower().EndsWith(".lua")) {
            File.Copy(srcFile, outFile, true);
            return;
        }
        bool isWin = true; 
        string luaexe = string.Empty;
        string args = string.Empty;
        string exedir = string.Empty;
        string currDir = Directory.GetCurrentDirectory();
        if (Application.platform == RuntimePlatform.WindowsEditor) {
            isWin = true;
            luaexe = "luajit.exe";
            args = "-b " + srcFile + " " + outFile;
            exedir = AppDataPath.Replace("assets", "") + "LuaEncoder/luajit/";
        } else if (Application.platform == RuntimePlatform.OSXEditor) {
            isWin = false;
            luaexe = "./luajit";
            args = "-b " + srcFile + " " + outFile;
            exedir = AppDataPath.Replace("assets", "") + "LuaEncoder/luajit_mac/";
        }
        Directory.SetCurrentDirectory(exedir);
        ProcessStartInfo info = new ProcessStartInfo();
        info.FileName = luaexe;
        info.Arguments = args;
        info.WindowStyle = ProcessWindowStyle.Hidden;
        info.UseShellExecute = isWin;
        info.ErrorDialog = true;
        Util.Log(info.FileName + " " + info.Arguments);

        Process pro = Process.Start(info);
        pro.WaitForExit();
        Directory.SetCurrentDirectory(currDir);
    }

}